From eee2ba42b6cde4b09d243a9abf6b4bfe9d93fcf6 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Mon, 25 Dec 2023 18:56:00 +0200 Subject: [PATCH] Added tasks 2874-2901 --- README.md | 20 ++++ .../readme.md | 63 ++++++++++ .../readme.md | 77 +++++++++++++ .../readme.md | 86 ++++++++++++++ .../readme.md | 40 +++++++ .../readme.md | 58 ++++++++++ .../readme.md | 55 +++++++++ .../g2801_2900/s2880_select_data/readme.md | 50 ++++++++ .../s2881_create_a_new_column/readme.md | 61 ++++++++++ .../s2882_drop_duplicate_rows/readme.md | 61 ++++++++++ .../s2883_drop_missing_data/readme.md | 58 ++++++++++ .../g2801_2900/s2884_modify_columns/readme.md | 57 +++++++++ .../g2801_2900/s2885_rename_columns/readme.md | 62 ++++++++++ .../s2886_change_data_type/readme.md | 53 +++++++++ .../s2887_fill_missing_data/readme.md | 56 +++++++++ .../s2888_reshape_data_concatenate/readme.md | 76 ++++++++++++ .../s2889_reshape_data_pivot/readme.md | 60 ++++++++++ .../s2890_reshape_data_melt/readme.md | 59 ++++++++++ .../s2891_method_chaining/readme.md | 72 ++++++++++++ .../readme.md | 68 +++++++++++ .../s2895_minimum_processing_time/readme.md | 8 +- .../readme.md | 108 ++++++++++++++++++ 22 files changed, 1307 insertions(+), 1 deletion(-) create mode 100644 src/main/java/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md create mode 100644 src/main/java/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md create mode 100644 src/main/java/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md create mode 100644 src/main/java/g2801_2900/s2877_create_a_dataframe_from_list/readme.md create mode 100644 src/main/java/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md create mode 100644 src/main/java/g2801_2900/s2879_display_the_first_three_rows/readme.md create mode 100644 src/main/java/g2801_2900/s2880_select_data/readme.md create mode 100644 src/main/java/g2801_2900/s2881_create_a_new_column/readme.md create mode 100644 src/main/java/g2801_2900/s2882_drop_duplicate_rows/readme.md create mode 100644 src/main/java/g2801_2900/s2883_drop_missing_data/readme.md create mode 100644 src/main/java/g2801_2900/s2884_modify_columns/readme.md create mode 100644 src/main/java/g2801_2900/s2885_rename_columns/readme.md create mode 100644 src/main/java/g2801_2900/s2886_change_data_type/readme.md create mode 100644 src/main/java/g2801_2900/s2887_fill_missing_data/readme.md create mode 100644 src/main/java/g2801_2900/s2888_reshape_data_concatenate/readme.md create mode 100644 src/main/java/g2801_2900/s2889_reshape_data_pivot/readme.md create mode 100644 src/main/java/g2801_2900/s2890_reshape_data_melt/readme.md create mode 100644 src/main/java/g2801_2900/s2891_method_chaining/readme.md create mode 100644 src/main/java/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md create mode 100644 src/main/java/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/readme.md diff --git a/README.md b/README.md index 53aadb29..969103ae 100644 --- a/README.md +++ b/README.md @@ -1816,11 +1816,31 @@ | # | Title | Difficulty | Tag | Time, ms | Time, % |------|----------------|-------------|-------------|----------|-------- +| 2901 |[Longest Unequal Adjacent Groups Subsequence II](src/main/java/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii)| Medium | Array, String, Dynamic_Programming | 40 | 92.26 | 2900 |[Longest Unequal Adjacent Groups Subsequence I](src/main/java/g2801_2900/s2900_longest_unequal_adjacent_groups_subsequence_i)| Medium | Array, String, Dynamic_Programming, Greedy | 1 | 100.00 | 2899 |[Last Visited Integers](src/main/java/g2801_2900/s2899_last_visited_integers)| Easy | Array, String, Simulation | 2 | 96.41 | 2897 |[Apply Operations on Array to Maximize Sum of Squares](src/main/java/g2801_2900/s2897_apply_operations_on_array_to_maximize_sum_of_squares)| Hard | Array, Hash_Table, Greedy, Bit_Manipulation | 29 | 98.00 | 2896 |[Apply Operations to Make Two Strings Equal](src/main/java/g2801_2900/s2896_apply_operations_to_make_two_strings_equal)| Medium | String, Dynamic_Programming | 1 | 100.00 | 2895 |[Minimum Processing Time](src/main/java/g2801_2900/s2895_minimum_processing_time)| Medium | Array, Sorting, Greedy | 23 | 99.30 +| 2894 |[Divisible and Non-divisible Sums Difference](src/main/java/g2801_2900/s2894_divisible_and_non_divisible_sums_difference)| Easy | Math | 1 | 92.30 +| 2891 |[Method Chaining](src/main/java/g2801_2900/s2891_method_chaining)| Easy || 412 | 99.23 +| 2890 |[Reshape Data: Melt](src/main/java/g2801_2900/s2890_reshape_data_melt)| Easy || 446 | 97.89 +| 2889 |[Reshape Data: Pivot](src/main/java/g2801_2900/s2889_reshape_data_pivot)| Easy || 416 | 99.87 +| 2888 |[Reshape Data: Concatenate](src/main/java/g2801_2900/s2888_reshape_data_concatenate)| Easy || 441 | 96.26 +| 2887 |[Fill Missing Data](src/main/java/g2801_2900/s2887_fill_missing_data)| Easy || 404 | 97.11 +| 2886 |[Change Data Type](src/main/java/g2801_2900/s2886_change_data_type)| Easy || 421 | 94.57 +| 2885 |[Rename Columns](src/main/java/g2801_2900/s2885_rename_columns)| Easy || 467 | 68.13 +| 2884 |[Modify Columns](src/main/java/g2801_2900/s2884_modify_columns)| Easy || 401 | 96.35 +| 2883 |[Drop Missing Data](src/main/java/g2801_2900/s2883_drop_missing_data)| Easy || 429 | 94.97 +| 2882 |[Drop Duplicate Rows](src/main/java/g2801_2900/s2882_drop_duplicate_rows)| Easy || 405 | 97.36 +| 2881 |[Create a New Column](src/main/java/g2801_2900/s2881_create_a_new_column)| Easy || 437 | 81.98 +| 2880 |[Select Data](src/main/java/g2801_2900/s2880_select_data)| Easy || 428 | 94.99 +| 2879 |[Display the First Three Rows](src/main/java/g2801_2900/s2879_display_the_first_three_rows)| Easy || 406 | 96.44 +| 2878 |[Get the Size of a DataFrame](src/main/java/g2801_2900/s2878_get_the_size_of_a_dataframe)| Easy || 413 | 94.68 +| 2877 |[Create a DataFrame from List](src/main/java/g2801_2900/s2877_create_a_dataframe_from_list)| Easy || 406 | 82.57 +| 2876 |[Count Visited Nodes in a Directed Graph](src/main/java/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph)| Hard | Dynamic_Programming, Graph, Memoization | 36 | 93.33 +| 2875 |[Minimum Size Subarray in Infinite Array](src/main/java/g2801_2900/s2875_minimum_size_subarray_in_infinite_array)| Medium | Array, Hash_Table, Prefix_Sum, Sliding_Window | 6 | 87.63 +| 2874 |[Maximum Value of an Ordered Triplet II](src/main/java/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii)| Medium | Array | 2 | 99.67 | 2873 |[Maximum Value of an Ordered Triplet I](src/main/java/g2801_2900/s2873_maximum_value_of_an_ordered_triplet_i)| Easy | Array | 0 | 100.00 | 2872 |[Maximum Number of K-Divisible Components](src/main/java/g2801_2900/s2872_maximum_number_of_k_divisible_components)| Hard | Dynamic_Programming, Depth_First_Search, Tree | 24 | 93.51 | 2871 |[Split Array Into Maximum Number of Subarrays](src/main/java/g2801_2900/s2871_split_array_into_maximum_number_of_subarrays)| Medium | Array, Greedy, Bit_Manipulation | 3 | 100.00 diff --git a/src/main/java/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md b/src/main/java/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md new file mode 100644 index 00000000..9ecbe6cc --- /dev/null +++ b/src/main/java/g2801_2900/s2874_maximum_value_of_an_ordered_triplet_ii/readme.md @@ -0,0 +1,63 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2874\. Maximum Value of an Ordered Triplet II + +Medium + +You are given a **0-indexed** integer array `nums`. + +Return _**the maximum value over all triplets of indices**_ `(i, j, k)` _such that_ `i < j < k`_._ If all such triplets have a negative value, return `0`. + +The **value of a triplet of indices** `(i, j, k)` is equal to `(nums[i] - nums[j]) * nums[k]`. + +**Example 1:** + +**Input:** nums = [12,6,1,2,7] + +**Output:** 77 + +**Explanation:** The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) \* nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. + +**Example 2:** + +**Input:** nums = [1,10,3,4,19] + +**Output:** 133 + +**Explanation:** The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) \* nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. + +**Example 3:** + +**Input:** nums = [1,2,3] + +**Output:** 0 + +**Explanation:** The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) \* nums[2] = -3. Hence, the answer would be 0. + +**Constraints:** + +* 3 <= nums.length <= 105 +* 1 <= nums[i] <= 106 + +## Solution + +```java +public class Solution { + public long maximumTripletValue(int[] nums) { + int[] diff = new int[nums.length]; + int tempMax = nums[0]; + for (int i = 1; i < diff.length - 1; i++) { + diff[i] = tempMax - nums[i]; + tempMax = Math.max(tempMax, nums[i]); + } + long max = Long.MIN_VALUE; + tempMax = nums[nums.length - 1]; + for (int i = nums.length - 2; i > 0; i--) { + max = Math.max(max, (long) tempMax * diff[i]); + tempMax = Math.max(tempMax, nums[i]); + } + return Math.max(max, 0); + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md b/src/main/java/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md new file mode 100644 index 00000000..cbd0b943 --- /dev/null +++ b/src/main/java/g2801_2900/s2875_minimum_size_subarray_in_infinite_array/readme.md @@ -0,0 +1,77 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2875\. Minimum Size Subarray in Infinite Array + +Medium + +You are given a **0-indexed** array `nums` and an integer `target`. + +A **0-indexed** array `infinite_nums` is generated by infinitely appending the elements of `nums` to itself. + +Return _the length of the **shortest** subarray of the array_ `infinite_nums` _with a sum equal to_ `target`_._ If there is no such subarray return `-1`. + +**Example 1:** + +**Input:** nums = [1,2,3], target = 5 + +**Output:** 2 + +**Explanation:** In this example infinite\_nums = [1,2,3,1,2,3,1,2,...]. The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. + +**Example 2:** + +**Input:** nums = [1,1,1,2,3], target = 4 + +**Output:** 2 + +**Explanation:** In this example infinite\_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. + +**Example 3:** + +**Input:** nums = [2,4,6,8], target = 3 + +**Output:** -1 + +**Explanation:** In this example infinite\_nums = [2,4,6,8,2,4,6,8,...]. It can be proven that there is no subarray with sum equal to target = 3. + +**Constraints:** + +* 1 <= nums.length <= 105 +* 1 <= nums[i] <= 105 +* 1 <= target <= 109 + +## Solution + +```java +public class Solution { + public int minSizeSubarray(int[] nums, int target) { + int sum = 0; + for (int num : nums) { + sum += num; + } + if (sum == 0) { + return -1; + } + int result = (target / sum) * nums.length; + sum = target % sum; + int currentSum = 0; + int min = nums.length; + int start = 0; + for (int i = 0; i < nums.length * 2; i++) { + currentSum += nums[i % nums.length]; + while (currentSum > sum) { + currentSum -= nums[start % nums.length]; + start++; + } + if (currentSum == sum) { + min = Math.min(min, i - start + 1); + } + } + if (min == nums.length) { + return -1; + } + return result + min; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md b/src/main/java/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md new file mode 100644 index 00000000..49363ed3 --- /dev/null +++ b/src/main/java/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/readme.md @@ -0,0 +1,86 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2876\. Count Visited Nodes in a Directed Graph + +Hard + +There is a **directed** graph consisting of `n` nodes numbered from `0` to `n - 1` and `n` directed edges. + +You are given a **0-indexed** array `edges` where `edges[i]` indicates that there is an edge from node `i` to node `edges[i]`. + +Consider the following process on the graph: + +* You start from a node `x` and keep visiting other nodes through edges until you reach a node that you have already visited before on this **same** process. + +Return _an array_ `answer` _where_ `answer[i]` _is the number of **different** nodes that you will visit if you perform the process starting from node_ `i`. + +**Example 1:** + +![](https://assets.leetcode.com/uploads/2023/08/31/graaphdrawio-1.png) + +**Input:** edges = [1,2,0,0] + +**Output:** [3,3,3,4] + +**Explanation:** We perform the process starting from each node in the following way: +- Starting from node 0, we visit the nodes 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 3. +- Starting from node 1, we visit the nodes 1 -> 2 -> 0 -> 1. The number of different nodes we visit is 3. +- Starting from node 2, we visit the nodes 2 -> 0 -> 1 -> 2. The number of different nodes we visit is 3. +- Starting from node 3, we visit the nodes 3 -> 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 4. + +**Example 2:** + +![](https://assets.leetcode.com/uploads/2023/08/31/graaph2drawio.png) + +**Input:** edges = [1,2,3,4,0] + +**Output:** [5,5,5,5,5] + +**Explanation:** Starting from any node we can visit every node in the graph in the process. + +**Constraints:** + +* `n == edges.length` +* 2 <= n <= 105 +* `0 <= edges[i] <= n - 1` +* `edges[i] != i` + +## Solution + +```java +import java.util.List; + +public class Solution { + public int[] countVisitedNodes(List edges) { + int n = edges.size(); + boolean[] visited = new boolean[n]; + int[] ans = new int[n]; + int[] level = new int[n]; + for (int i = 0; i < n; i++) { + if (!visited[i]) { + visit(edges, 0, i, ans, visited, level); + } + } + return ans; + } + + private int[] visit( + List edges, int count, int curr, int[] ans, boolean[] visited, int[] level) { + if (ans[curr] != 0) { + return new int[] {-1, ans[curr]}; + } + if (visited[curr]) { + return new int[] {level[curr], count - level[curr]}; + } + level[curr] = count; + visited[curr] = true; + int[] ret = visit(edges, count + 1, edges.get(curr), ans, visited, level); + if (ret[0] == -1 || count < ret[0]) { + ret[1]++; + } + ans[curr] = ret[1]; + return ret; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2877_create_a_dataframe_from_list/readme.md b/src/main/java/g2801_2900/s2877_create_a_dataframe_from_list/readme.md new file mode 100644 index 00000000..4a5262e2 --- /dev/null +++ b/src/main/java/g2801_2900/s2877_create_a_dataframe_from_list/readme.md @@ -0,0 +1,40 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2877\. Create a DataFrame from List + +Easy + +Write a solution to **create** a DataFrame from a 2D list called `student_data`. This 2D list contains the IDs and ages of some students. + +The DataFrame should have two columns, `student_id` and `age`, and be in the same order as the original 2D list. + +The result format is in the following example. + +**Example 1:** + +**Input:** student\_data: `[ [1, 15], [2, 11], [3, 11], [4, 20] ]` + +**Output:** + + +------------+-----+ + | student_id | age | + +------------+-----+ + | 1 | 15 | + | 2 | 11 | + | 3 | 11 | + | 4 | 20 | + +------------+-----+ + +**Explanation:** A DataFrame was created on top of student\_data, with two columns named `student_id` and `age`. + +## Solution + +```python +import pandas as pd + +def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: + column_name = ['student_id','age'] + result = pd.DataFrame(student_data, columns=column_name) + return result +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md b/src/main/java/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md new file mode 100644 index 00000000..b30f1c64 --- /dev/null +++ b/src/main/java/g2801_2900/s2878_get_the_size_of_a_dataframe/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2878\. Get the Size of a DataFrame + +Easy + +DataFrame `players:` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | player_id | int | + | name | object | + | age | int | + | position | object | + | ... | ... | + +-------------+--------+ + +Write a solution to calculate and display the **number of rows and columns** of `players`. + +Return the result as an array: + +`[number of rows, number of columns]` + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-----------+----------+-----+-------------+--------------------+ + | player_id | name | age | position | team | + +-----------+----------+-----+-------------+--------------------+ + | 846 | Mason | 21 | Forward | RealMadrid | + | 749 | Riley | 30 | Winger | Barcelona | + | 155 | Bob | 28 | Striker | ManchesterUnited | + | 583 | Isabella | 32 | Goalkeeper | Liverpool | + | 388 | Zachary | 24 | Midfielder | BayernMunich | + | 883 | Ava | 23 | Defender | Chelsea | + | 355 | Violet | 18 | Striker | Juventus | + | 247 | Thomas | 27 | Striker | ParisSaint-Germain | + | 761 | Jack | 33 | Midfielder | ManchesterCity | + | 642 | Charlie | 36 | Center-back | Arsenal | + +-----------+----------+-----+-------------+--------------------+ + +**Output:** [10, 5] + +**Explanation:** This DataFrame contains 10 rows and 5 columns. + +## Solution + +```python +import pandas as pd + +def getDataframeSize(players: pd.DataFrame) -> List[int]: + return[players.shape[0], players.shape[1]] +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2879_display_the_first_three_rows/readme.md b/src/main/java/g2801_2900/s2879_display_the_first_three_rows/readme.md new file mode 100644 index 00000000..401e0226 --- /dev/null +++ b/src/main/java/g2801_2900/s2879_display_the_first_three_rows/readme.md @@ -0,0 +1,55 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2879\. Display the First Three Rows + +Easy + +DataFrame: `employees` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | employee_id | int | + | name | object | + | department | object | + | salary | int | + +-------------+--------+ + +Write a solution to display the **first `3`** rows of this DataFrame. + +**Example 1:** + +**Input:** DataFrame employees + + +-------------+-----------+-----------------------+--------+ + | employee_id | name | department | salary | + +-------------+-----------+-----------------------+--------+ + | 3 | Bob | Operations | 48675 | + | 90 | Alice | Sales | 11096 | + | 9 | Tatiana | Engineering | 33805 | + | 60 | Annabelle | InformationTechnology | 37678 | + | 49 | Jonathan | HumanResources | 23793 | + | 43 | Khaled | Administration | 40454 | + +-------------+-----------+-----------------------+--------+ + +**Output:** + + +-------------+---------+-------------+--------+ + | employee_id | name | department | salary | + +-------------+---------+-------------+--------+ + | 3 | Bob | Operations | 48675 | + | 90 | Alice | Sales | 11096 | + | 9 | Tatiana | Engineering | 33805 | + +-------------+---------+-------------+--------+ + +**Explanation:** Only the first 3 rows are displayed. + +## Solution + +```python +import pandas as pd + +def selectFirstRows(zs: pd.DataFrame) -> pd.DataFrame: + return zs.head(3) +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2880_select_data/readme.md b/src/main/java/g2801_2900/s2880_select_data/readme.md new file mode 100644 index 00000000..dc921f29 --- /dev/null +++ b/src/main/java/g2801_2900/s2880_select_data/readme.md @@ -0,0 +1,50 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2880\. Select Data + +Easy + +DataFrame students + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +Write a solution to select the name and age of the student with `student_id = 101`. + +The result format is in the following example. + +**Example 1: Input:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 101 | Ulysses | 13 | + | 53 | William | 10 | + | 128 | Henry | 6 | + | 3 | Henry | 11 | + +------------+---------+-----+ + +**Output:** + + +---------+-----+ + | name | age | + +---------+-----+ + | Ulysses | 13 | + +---------+-----+ + +**Explanation:** Student Ulysses has student_id = 101, we select the name and age. + +## Solution + +```python +import pandas as pd + +def selectData(students: pd.DataFrame) -> pd.DataFrame: + return students[students.student_id == 101][['name','age']] +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2881_create_a_new_column/readme.md b/src/main/java/g2801_2900/s2881_create_a_new_column/readme.md new file mode 100644 index 00000000..299b9c5d --- /dev/null +++ b/src/main/java/g2801_2900/s2881_create_a_new_column/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2881\. Create a New Column + +Easy + +DataFrame `employees` + + +-------------+--------+ + | Column Name | Type. | + +-------------+--------+ + | name | object | + | salary | int. | + +-------------+--------+ + +A company plans to provide its employees with a bonus. + +Write a solution to create a new column name `bonus` that contains the **doubled values** of the `salary` column. + +The result format is in the following example. + +**Example 1:** + +**Input:** DataFrame employees + + +---------+--------+ + | name | salary | + +---------+--------+ + | Piper | 4548 | + | Grace | 28150 | + | Georgia | 1103 | + | Willow | 6593 | + | Finn | 74576 | + | Thomas | 24433 | + +---------+--------+ + +**Output:** + + +---------+--------+--------+ + | name | salary | bonus | + +---------+--------+--------+ + | Piper | 4548 | 9096 | + | Grace | 28150 | 56300 | + | Georgia | 1103 | 2206 | + | Willow | 6593 | 13186 | + | Finn | 74576 | 149152 | + | Thomas | 24433 | 48866 | + +---------+--------+--------+ + +**Explanation:** A new column bonus is created by doubling the value in the column salary. + +## Solution + +```python +import pandas as pd + +def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: + employees["bonus"] = employees["salary"] * 2 + return employees +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2882_drop_duplicate_rows/readme.md b/src/main/java/g2801_2900/s2882_drop_duplicate_rows/readme.md new file mode 100644 index 00000000..49db005f --- /dev/null +++ b/src/main/java/g2801_2900/s2882_drop_duplicate_rows/readme.md @@ -0,0 +1,61 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2882\. Drop Duplicate Rows + +Easy + +DataFrame customers + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | customer_id | int | + | name | object | + | email | object | + +-------------+--------+ + +There are some duplicate rows in the DataFrame based on the `email` column. + +Write a solution to remove these duplicate rows and keep only the **first** occurrence. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-------------+---------+---------------------+ + | customer_id | name | email | + +-------------+---------+---------------------+ + | 1 | Ella | emily@example.com | + | 2 | David | michael@example.com | + | 3 | Zachary | sarah@example.com | + | 4 | Alice | john@example.com | + | 5 | Finn | john@example.com | + | 6 | Violet | alice@example.com | + +-------------+---------+---------------------+ + +**Output:** + + +-------------+---------+---------------------+ + | customer_id | name | email | + +-------------+---------+---------------------+ + | 1 | Ella | emily@example.com | + | 2 | David | michael@example.com | + | 3 | Zachary | sarah@example.com | + | 4 | Alice | john@example.com | + | 6 | Violet | alice@example.com | + +-------------+---------+---------------------+ + +**Explanation:** Alic (customer_id = 4) and Finn (customer_id = 5) both use john@example.com, so only the first occurrence of this email is retained. + +## Solution + +```python +import pandas as pd + +def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: + customers.drop_duplicates(subset='email', keep='first', inplace=True) + return customers +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2883_drop_missing_data/readme.md b/src/main/java/g2801_2900/s2883_drop_missing_data/readme.md new file mode 100644 index 00000000..87abc423 --- /dev/null +++ b/src/main/java/g2801_2900/s2883_drop_missing_data/readme.md @@ -0,0 +1,58 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2883\. Drop Missing Data + +Easy + +DataFrame students + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +There are some rows having missing values in the `name` column. + +Write a solution to remove the rows with missing values. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 32 | Piper | 5 | + | 217 | None | 19 | + | 779 | Georgia | 20 | + | 849 | Willow | 14 | + +------------+---------+-----+ + +**Output:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 32 | Piper | 5 | + | 779 | Georgia | 20 | + | 849 | Willow | 14 | + +------------+---------+-----+ + +**Explanation:** Student with id 217 havs empty value in the name column, so it will be removed. + +## Solution + +```python +import pandas as pd + +def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: + r = pd.DataFrame(students) + r.dropna(subset='name', inplace=True) + return r +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2884_modify_columns/readme.md b/src/main/java/g2801_2900/s2884_modify_columns/readme.md new file mode 100644 index 00000000..b17fc6fc --- /dev/null +++ b/src/main/java/g2801_2900/s2884_modify_columns/readme.md @@ -0,0 +1,57 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2884\. Modify Columns + +Easy + +DataFrame `employees` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | name | object | + | salary | int | + +-------------+--------+ + +A company intends to give its employees a pay rise. + +Write a solution to **modify** the `salary` column by multiplying each salary by 2. + +The result format is in the following example. + +**Example 1:** + +**Input:** DataFrame employees + + +---------+--------+ + | name | salary | + +---------+--------+ + | Jack | 19666 | + | Piper | 74754 | + | Mia | 62509 | + | Ulysses | 54866 | + +---------+--------+ + +**Output:** + + +---------+--------+ + | name | salary | + +---------+--------+ + | Jack | 39332 | + | Piper | 149508 | + | Mia | 125018 | + | Ulysses | 109732 | + +---------+--------+ + +**Explanation:** Every salary has been doubled. + +## Solution + +```python +import pandas as pd + +def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame: + employees['salary'] = employees['salary'] * 2 + return employees +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2885_rename_columns/readme.md b/src/main/java/g2801_2900/s2885_rename_columns/readme.md new file mode 100644 index 00000000..fb9d4d96 --- /dev/null +++ b/src/main/java/g2801_2900/s2885_rename_columns/readme.md @@ -0,0 +1,62 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2885\. Rename Columns + +Easy + +DataFrame `students` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | id | int | + | first | object | + | last | object | + | age | int | + +-------------+--------+ + +Write a solution to rename the columns as follows: + +* `id` to `student_id` +* `first` to `first_name` +* `last` to `last_name` +* `age` to `age_in_years` + +The result format is in the following example. + +**Example 1:** **Input:** + + +----+---------+----------+-----+ + | id | first | last | age | + +----+---------+----------+-----+ + | 1 | Mason | King | 6 | + | 2 | Ava | Wright | 7 | + | 3 | Taylor | Hall | 16 | + | 4 | Georgia | Thompson | 18 | + | 5 | Thomas | Moore | 10 | + +----+---------+----------+-----+ + +**Output:** + + +------------+------------+-----------+--------------+ + | student_id | first_name | last_name | age_in_years | + +------------+------------+-----------+--------------+ + | 1 | Mason | King | 6 | + | 2 | Ava | Wright | 7 | + | 3 | Taylor | Hall | 16 | + | 4 | Georgia | Thompson | 18 | + | 5 | Thomas | Moore | 10 | + +------------+------------+-----------+--------------+ + +**Explanation:** The column names are changed accordingly. + +## Solution + +```python +import pandas as pd + +def renameColumns(students: pd.DataFrame) -> pd.DataFrame: + students.rename(columns={'id': 'student_id', 'first': 'first_name', 'last': 'last_name', 'age': 'age_in_years'}, inplace=True) + return students +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2886_change_data_type/readme.md b/src/main/java/g2801_2900/s2886_change_data_type/readme.md new file mode 100644 index 00000000..b8ed45be --- /dev/null +++ b/src/main/java/g2801_2900/s2886_change_data_type/readme.md @@ -0,0 +1,53 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2886\. Change Data Type + +Easy + +DataFrame `students` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + | grade | float | + +-------------+--------+ + +Write a solution to correct the errors: + +The `grade` column is stored as floats, convert it to integers. + +The result format is in the following example. + +**Example 1:** **Input:** DataFrame students: + + +------------+------+-----+-------+ + | student_id | name | age | grade | + +------------+------+-----+-------+ + | 1 | Ava | 6 | 73.0 | + | 2 | Kate | 15 | 87.0 | + +------------+------+-----+-------+ + +**Output:** + + +------------+------+-----+-------+ + | student_id | name | age | grade | + +------------+------+-----+-------+ + | 1 | Ava | 6 | 73 | + | 2 | Kate | 15 | 87 | + +------------+------+-----+-------+ + +**Explanation:** The data types of the column grade is converted to int. + +## Solution + +```python +import pandas as pd + +def changeDatatype(students: pd.DataFrame) -> pd.DataFrame: + students['grade'] = students['grade'].astype(int) + return students +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2887_fill_missing_data/readme.md b/src/main/java/g2801_2900/s2887_fill_missing_data/readme.md new file mode 100644 index 00000000..2ec984c6 --- /dev/null +++ b/src/main/java/g2801_2900/s2887_fill_missing_data/readme.md @@ -0,0 +1,56 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2887\. Fill Missing Data + +Easy + +DataFrame `products` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | name | object | + | quantity | int | + | price | int | + +-------------+--------+ + +Write a solution to fill in the missing value as **0** in the `quantity` column. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-----------------+----------+-------+ + | name | quantity | price | + +-----------------+----------+-------+ + | Wristwatch | None | 135 | + | WirelessEarbuds | None | 821 | + | GolfClubs | 779 | 9319 | + | Printer | 849 | 3051 | + +-----------------+----------+-------+ + +**Output:** + + +-----------------+----------+-------+ + | name | quantity | price | + +-----------------+----------+-------+ + | Wristwatch | 0 | 135 | + | WirelessEarbuds | 0 | 821 | + | GolfClubs | 779 | 9319 | + | Printer | 849 | 3051 | + +-----------------+----------+-------+ + +**Explanation:** The quantity for Wristwatch and WirelessEarbuds are filled by 0. + +## Solution + +```python +import pandas as pd + +def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame: + products['quantity'].fillna(0, inplace=True) + return products +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2888_reshape_data_concatenate/readme.md b/src/main/java/g2801_2900/s2888_reshape_data_concatenate/readme.md new file mode 100644 index 00000000..58103c1c --- /dev/null +++ b/src/main/java/g2801_2900/s2888_reshape_data_concatenate/readme.md @@ -0,0 +1,76 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2888\. Reshape Data: Concatenate + +Easy + +DataFrame `df1` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +DataFrame `df2` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | student_id | int | + | name | object | + | age | int | + +-------------+--------+ + +Write a solution to concatenate these two DataFrames **vertically** into one DataFrame. + +The result format is in the following example. + +**Example 1:** + +**Input: df1** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 1 | Mason | 8 | + | 2 | Ava | 6 | + | 3 | Taylor | 15 | + | 4 | Georgia | 17 | + +------------+---------+-----+ + +**df2** + + +------------+------+-----+ + | student_id | name | age | + +------------+------+-----+ + | 5 | Leo | 7 | + | 6 | Alex | 7 | + +------------+------+-----+ + +**Output:** + + +------------+---------+-----+ + | student_id | name | age | + +------------+---------+-----+ + | 1 | Mason | 8 | + | 2 | Ava | 6 | + | 3 | Taylor | 15 | + | 4 | Georgia | 17 | + | 5 | Leo | 7 | + | 6 | Alex | 7 | + +------------+---------+-----+ + +**Explanation:** The two DataFramess are stacked vertically, and their rows are combined. + +## Solution + +```python +import pandas as pd + +def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame: + return pd.concat([df1, df2], ignore_index=True) +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2889_reshape_data_pivot/readme.md b/src/main/java/g2801_2900/s2889_reshape_data_pivot/readme.md new file mode 100644 index 00000000..cf4e7827 --- /dev/null +++ b/src/main/java/g2801_2900/s2889_reshape_data_pivot/readme.md @@ -0,0 +1,60 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2889\. Reshape Data: Pivot + +Easy + +DataFrame `weather` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | city | object | + | month | object | + | temperature | int | + +-------------+--------+ + +Write a solution to **pivot** the data so that each row represents temperatures for a specific month, and each city is a separate column. + +The result format is in the following example. + +**Example 1:** **Input:** + + +--------------+----------+-------------+ + | city | month | temperature | + +--------------+----------+-------------+ + | Jacksonville | January | 13 | + | Jacksonville | February | 23 | + | Jacksonville | March | 38 | + | Jacksonville | April | 5 | + | Jacksonville | May | 34 | + | ElPaso | January | 20 | + | ElPaso | February | 6 | + | ElPaso | March | 26 | + | ElPaso | April | 2 | + | ElPaso | May | 43 | + +--------------+----------+-------------+ + +**Output:**` + + +----------+--------+--------------+ + | month | ElPaso | Jacksonville | + +----------+--------+--------------+ + | April | 2 | 5 | + | February | 6 | 23 | + | January | 20 | 13 | + | March | 26 | 38 | + | May | 43 | 34 | + +----------+--------+--------------+` + +**Explanation:** The table is pivoted, each column represents a city, and each row represents a specific month. + +## Solution + +```python +import pandas as pd + +def pivotTable(weather: pd.DataFrame) -> pd.DataFrame: + return weather.pivot(index='month', columns='city', values='temperature') +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2890_reshape_data_melt/readme.md b/src/main/java/g2801_2900/s2890_reshape_data_melt/readme.md new file mode 100644 index 00000000..46864f55 --- /dev/null +++ b/src/main/java/g2801_2900/s2890_reshape_data_melt/readme.md @@ -0,0 +1,59 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2890\. Reshape Data: Melt + +Easy + +DataFrame `report` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | product | object | + | quarter_1 | int | + | quarter_2 | int | + | quarter_3 | int | + | quarter_4 | int | + +-------------+--------+ + +Write a solution to **reshape** the data so that each row represents sales data for a product in a specific quarter. + +The result format is in the following example. + +**Example 1:** + +**Input:** + + +-------------+-----------+-----------+-----------+-----------+ + | product | quarter_1 | quarter_2 | quarter_3 | quarter_4 | + +-------------+-----------+-----------+-----------+-----------+ + | Umbrella | 417 | 224 | 379 | 611 | + | SleepingBag | 800 | 936 | 93 | 875 | + +-------------+-----------+-----------+-----------+-----------+ + +**Output:** + + +-------------+-----------+-------+ + | product | quarter | sales | + +-------------+-----------+-------+ + | Umbrella | quarter_1 | 417 | + | SleepingBag | quarter_1 | 800 | + | Umbrella | quarter_2 | 224 | + | SleepingBag | quarter_2 | 936 | + | Umbrella | quarter_3 | 379 | + | SleepingBag | quarter_3 | 93 | + | Umbrella | quarter_4 | 611 | + | SleepingBag | quarter_4 | 875 | + +-------------+-----------+-------+ + +**Explanation:** The DataFrame is reshaped from wide to long format. Each row represents the sales of a product in a quarter. + +## Solution + +```python +import pandas as pd + +def meltTable(report: pd.DataFrame) -> pd.DataFrame: + return report.melt(id_vars='product', var_name='quarter', value_name='sales') +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2891_method_chaining/readme.md b/src/main/java/g2801_2900/s2891_method_chaining/readme.md new file mode 100644 index 00000000..1fd20e2c --- /dev/null +++ b/src/main/java/g2801_2900/s2891_method_chaining/readme.md @@ -0,0 +1,72 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2891\. Method Chaining + +Easy + +DataFrame `animals` + + +-------------+--------+ + | Column Name | Type | + +-------------+--------+ + | name | object | + | species | object | + | age | int | + | weight | int | + +-------------+--------+ + +Write a solution to list the names of animals that weigh **strictly more than** `100` kilograms. + +Return the animals sorted by weight in **descending order**. + +The result format is in the following example. + +**Example 1:** + +**Input:** DataFrame animals: + + +----------+---------+-----+--------+ + | name | species | age | weight | + +----------+---------+-----+--------+ + | Tatiana | Snake | 98 | 464 | + | Khaled | Giraffe | 50 | 41 | + | Alex | Leopard | 6 | 328 | + | Jonathan | Monkey | 45 | 463 | + | Stefan | Bear | 100 | 50 | + | Tommy | Panda | 26 | 349 | + +----------+---------+-----+--------+ + +**Output:** + + +----------+ + | name | + +----------+ + | Tatiana | + | Jonathan | + | Tommy | + | Alex | + +----------+ + +**Explanation:** All animals weighing more than 100 should be included in the results table. Tatiana's weight is 464, Jonathan's weight is 463, Tommy's weight is 349, and Alex's weight is 328. The results should be sorted in descending order of weight. + +In Pandas, **method chaining** enables us to perform operations on a DataFrame without breaking up each operation into a separate line or creating multiple temporary variables. + +Can you complete this task in just **one line** of code using method chaining? + +## Solution + +```python +import pandas as pd + +def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame: + animal_data = {} + for index in animals.index: + animal = animals.iloc[index] + if animal['weight'] > 100: + animal_data[animal['name']] = animal['weight'] + + animal_data = dict(sorted(animal_data.items() , key = lambda x : x[1] , reverse = True)) + result = pd.DataFrame(animal_data.keys() , columns = ['name']) + return result +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md b/src/main/java/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md new file mode 100644 index 00000000..75512e0a --- /dev/null +++ b/src/main/java/g2801_2900/s2894_divisible_and_non_divisible_sums_difference/readme.md @@ -0,0 +1,68 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2894\. Divisible and Non-divisible Sums Difference + +Easy + +You are given positive integers `n` and `m`. + +Define two integers, `num1` and `num2`, as follows: + +* `num1`: The sum of all integers in the range `[1, n]` that are **not divisible** by `m`. +* `num2`: The sum of all integers in the range `[1, n]` that are **divisible** by `m`. + +Return _the integer_ `num1 - num2`. + +**Example 1:** + +**Input:** n = 10, m = 3 + +**Output:** 19 + +**Explanation:** In the given example: +- Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. +- Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. + +**Example 2:** + +**Input:** n = 5, m = 6 + +**Output:** 15 + +**Explanation:** In the given example: +- Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. +- Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. + +**Example 3:** + +**Input:** n = 5, m = 1 + +**Output:** -15 + +**Explanation:** In the given example: +- Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. +- Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. + +**Constraints:** + +* `1 <= n, m <= 1000` + +## Solution + +```java +public class Solution { + public int differenceOfSums(int n, int m) { + int sum1 = 0; + int sum2 = 0; + for (int i = 1; i <= n; i++) { + if (i % m == 0) { + sum1 += i; + } else { + sum2 += i; + } + } + return sum2 - sum1; + } +} +``` \ No newline at end of file diff --git a/src/main/java/g2801_2900/s2895_minimum_processing_time/readme.md b/src/main/java/g2801_2900/s2895_minimum_processing_time/readme.md index e752640e..f3395b72 100644 --- a/src/main/java/g2801_2900/s2895_minimum_processing_time/readme.md +++ b/src/main/java/g2801_2900/s2895_minimum_processing_time/readme.md @@ -35,7 +35,13 @@ Hence, it can be shown that the minimum time taken to execute all the tasks is 1 **Explanation:** -It's optimal to assign the tasks at indexes 1, 4, 5, 6 to the first processor which becomes available at time = 10, and the tasks at indexes 0, 2, 3, 7 to the second processor which becomes available at time = 20. Time taken by the first processor to finish execution of all tasks = max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18. Time taken by the second processor to finish execution of all tasks = max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23. Hence, it can be shown that the minimum time taken to execute all the tasks is 23. +It's optimal to assign the tasks at indexes 1, 4, 5, 6 to the first processor which becomes available at time = 10, and the tasks at indexes 0, 2, 3, 7 to the second processor which becomes available at time = 20. + +Time taken by the first processor to finish execution of all tasks = max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18. + +Time taken by the second processor to finish execution of all tasks = max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23. + +Hence, it can be shown that the minimum time taken to execute all the tasks is 23. **Constraints:** diff --git a/src/main/java/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/readme.md b/src/main/java/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/readme.md new file mode 100644 index 00000000..0a40e7e5 --- /dev/null +++ b/src/main/java/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/readme.md @@ -0,0 +1,108 @@ +[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Java?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Java) +[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Java?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Java/fork) + +## 2901\. Longest Unequal Adjacent Groups Subsequence II + +Medium + +You are given an integer `n`, a **0-indexed** string array `words`, and a **0-indexed** array `groups`, both arrays having length `n`. + +The **hamming distance** between two strings of equal length is the number of positions at which the corresponding characters are **different**. + +You need to select the **longest** **subsequence** from an array of indices `[0, 1, ..., n - 1]`, such that for the subsequence denoted as [i0, i1, ..., ik - 1] having length `k`, the following holds: + +* For **adjacent** indices in the subsequence, their corresponding groups are **unequal**, i.e., groups[ij] != groups[ij + 1], for each `j` where `0 < j + 1 < k`. +* words[ij] and words[ij + 1] are **equal** in length, and the **hamming distance** between them is `1`, where `0 < j + 1 < k`, for all indices in the subsequence. + +Return _a string array containing the words corresponding to the indices **(in order)** in the selected subsequence_. If there are multiple answers, return _any of them_. + +A **subsequence** of an array is a new array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements. + +**Note:** strings in `words` may be **unequal** in length. + +**Example 1:** + +**Input:** n = 3, words = ["bab","dab","cab"], groups = [1,2,2] + +**Output:** ["bab","cab"] + +**Explanation:** A subsequence that can be selected is [0,2]. +- groups[0] != groups[2] +- words[0].length == words[2].length, and the hamming distance between them is 1. + +So, a valid answer is [words[0],words[2]] = ["bab","cab"]. Another subsequence that can be selected is [0,1]. +- groups[0] != groups[1] +- words[0].length == words[1].length, and the hamming distance between them is 1. + +So, another valid answer is [words[0],words[1]] = ["bab","dab"]. It can be shown that the length of the longest subsequence of indices that satisfies the conditions is 2. + +**Example 2:** + +**Input:** n = 4, words = ["a","b","c","d"], groups = [1,2,3,4] + +**Output:** ["a","b","c","d"] + +**Explanation:** We can select the subsequence [0,1,2,3]. It satisfies both conditions. Hence, the answer is [words[0],words[1],words[2],words[3]] = ["a","b","c","d"]. It has the longest length among all subsequences of indices that satisfy the conditions. Hence, it is the only answer. + +**Constraints:** + +* `1 <= n == words.length == groups.length <= 1000` +* `1 <= words[i].length <= 10` +* `1 <= groups[i] <= n` +* `words` consists of **distinct** strings. +* `words[i]` consists of lowercase English letters. + +## Solution + +```java +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class Solution { + public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + int[] check = new int[groups.length]; + int[] before = new int[groups.length]; + Arrays.fill(check, 1); + Arrays.fill(before, -1); + int index = 0; + int max = 1; + for (int i = 1; i < n; i++) { + for (int j = i - 1; j >= 0; j--) { + if (groups[i] != groups[j] && ham(words[i], words[j]) && check[j] + 1 > check[i]) { + check[i] = check[j] + 1; + before[i] = j; + if (check[i] > max) { + max = check[i]; + index = i; + } + } + } + } + List ans = new ArrayList<>(); + while (index >= 0) { + ans.add(words[index]); + index = before[index]; + } + Collections.reverse(ans); + return ans; + } + + private boolean ham(String s1, String s2) { + if (s1.length() != s2.length()) { + return false; + } + int count = 0; + for (int i = 0; i < s1.length(); i++) { + if (s1.charAt(i) != s2.charAt(i)) { + count++; + } + if (count > 1) { + return false; + } + } + return count == 1; + } +} +``` \ No newline at end of file